package com.xieyx.licenseplate;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static android.view.View.OVER_SCROLL_NEVER;

public class LicensePlateDialog extends Dialog {

    /**
     * 车牌简称
     */
    private List<String> provinceList = new ArrayList<>();
    /**
     * 0~9,A~Z(车牌里没有I、O字母)
     */
    private List<String> numList = new ArrayList<>();
    /**
     * 电动车车牌
     */
    private List<String> electricList = new ArrayList<>();
    /**
     * 键盘的背景颜色
     */
    private final int backgroundColor = Color.parseColor("#e9e9e9");
    /**
     * 键盘文字颜色
     */
    private final int keyTextColor = Color.parseColor("#333333");
    /**
     * 键盘列数
     */
    private final int spanCount = 6;
    /**
     * 键盘 键的间隔
     */
    private final int keyButtonMargin = 15;
    /**
     * 键盘上下左右的边距
     */
    private final int keyboardPadding = 15;
    /**
     * 按键点击回调
     */
    private OnKeyClickListener onKeyClickListener;

    private KeyAdapter keyAdapter;

    private Context mContext;

    private RecyclerView recyclerView;

    public LicensePlateDialog(Context context) {
        super(context,R.style.common_dialog);
        mContext = context;
    }

    public LicensePlateDialog(Context context, int themeResId) {
        super(context, themeResId);
        mContext = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_license_plate);
        recyclerView = findViewById(R.id.recycler_view);
        initKeys();
        recyclerView.setOverScrollMode(OVER_SCROLL_NEVER);
        recyclerView.setLayoutManager(new GridLayoutManager(mContext, spanCount));
        recyclerView.addItemDecoration(new RecycleGridDivider(keyButtonMargin));
        int padding = dip2px(mContext, keyboardPadding);
        recyclerView.setPadding(padding, padding, padding, padding);
        keyAdapter = new KeyAdapter(new onViewClick());
        recyclerView.setAdapter(keyAdapter);
        keyAdapter.setNewData(provinceList);
        setCanceledOnTouchOutside(true);
    }

    public void showDiaLog(){
        this.show();
        // 设置相关位置，一定要在 show()之后
        Window window = this.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.getDecorView().setPadding(0, 0, 0, 0);
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.gravity = Gravity.BOTTOM;
        window.setAttributes(params);
    }

    /**
     * 初始化按键
     */
    private void initKeys() {
        String[] province = mContext.getResources().getStringArray(R.array.province);
        String[] num = mContext.getResources().getStringArray(R.array.nums);
        String[] electric = mContext.getResources().getStringArray(R.array.electric);
        Collections.addAll(provinceList, province);
        Collections.addAll(numList, num);
        Collections.addAll(electricList, electric);
    }
    /**
     * 隐藏软键盘()
     */
    public void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     *切换数字键盘
     */
    public void switchNum(){
        keyAdapter.setNewData(numList);
    }

    /**
     *切换省键盘
     */
    public void switchProvince(){
        keyAdapter.setNewData(provinceList);
    }

    /**
     *切换电动车 城市选择
     */
    public void switchElectricCityList(){
        keyAdapter.setNewData(electricList);
    }

    /**
     *切换电动车 区选择
     */
    public void switchElectricAreaList(String city){
        List<String> areaList = new ArrayList<>();
        switch (city){
            case "漳州":
                String[] area1 = mContext.getResources().getStringArray(R.array.zz);
                Collections.addAll(areaList, area1);
                break;

            case "福州":
                String[] area2 = mContext.getResources().getStringArray(R.array.fz);
                Collections.addAll(areaList, area2);
                break;

            case "泉州":
                String[] area3 = mContext.getResources().getStringArray(R.array.qz);
                Collections.addAll(areaList, area3);
                break;

            case "厦门":
                String[] area4 = mContext.getResources().getStringArray(R.array.xm);
                Collections.addAll(areaList, area4);
                break;

            case "莆田":
                String[] area5 = mContext.getResources().getStringArray(R.array.pt);
                Collections.addAll(areaList, area5);
                break;

            case "三明":
                String[] area6 = mContext.getResources().getStringArray(R.array.sm);
                Collections.addAll(areaList, area6);
                break;
        }
        keyAdapter.setNewData(areaList);
    }



    private class onViewClick implements View.OnClickListener{

        @Override
        public void onClick(View view) {
            TextView tvKey = view.findViewById(R.id.tv_key);
            String key = tvKey.getText().toString();
            if (key.equals("ABC\n123")) {
                //键盘切换
                keyAdapter.setNewData(numList);
                return;
            } else if (key.equals("省")) {
                keyAdapter.setNewData(provinceList);
                return;
            }
            if (onKeyClickListener != null) {
                onKeyClickListener.onKeyClick(key);
            }
        }
    }


    private class KeyAdapter extends RecyclerView.Adapter<KeyAdapter.KeyViewHolder> {

        private List<String> list = new ArrayList<>();
        private onViewClick listener;

        public KeyAdapter(onViewClick listener) {
            this.listener = listener;
        }

        @NonNull
        @Override
        public KeyAdapter.KeyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_key, parent, false);
            return new KeyViewHolder(view);
        }


        @Override
        public void onBindViewHolder(@NonNull KeyAdapter.KeyViewHolder holder, int position) {
            String key = list.get(position);
            holder.tvKey.setText(key);
            holder.itemView.setOnClickListener(listener);
            if (TextUtils.isEmpty(key)) {
                holder.itemView.setBackgroundResource(0);
                //键盘类型切换按键
            } else if (key.equals("ABC\n123") || key.equals("省")) {
                holder.tvKey.setTextSize(16);
                holder.itemView.setBackgroundResource(R.drawable.licenseplate_solid_2dp_00a1ea);
                holder.tvKey.setTextColor(Color.WHITE);
            }else if(key.equals("无牌")){
                holder.tvKey.setTextSize(16);
                holder.itemView.setBackgroundResource(R.drawable.licenseplate_solid_2dp_00a1ea);
                holder.tvKey.setTextColor(Color.WHITE);
            } else if(key.equals("删")){
                holder.tvKey.setTextSize(16);
                holder.itemView.setBackgroundResource(R.drawable.licenseplate_solid_2dp_00a1ea);
                holder.tvKey.setTextColor(Color.WHITE);
            }else {
                holder.tvKey.setTextSize(18);
                holder.itemView.setBackgroundResource(R.drawable.licenseplate_solid_2dp_white);
                holder.tvKey.setTextColor(keyTextColor);
            }

        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        public void setNewData(List<String> list) {
            this.list.clear();
            this.list.addAll(list);
            notifyDataSetChanged();
        }

        private class KeyViewHolder extends RecyclerView.ViewHolder {

            private TextView tvKey;

            public KeyViewHolder(@NonNull View itemView) {
                super(itemView);
                tvKey = itemView.findViewById(R.id.tv_key);
            }
        }
    }

    public class RecycleGridDivider extends RecyclerView.ItemDecoration {

        /**
         * 分割线宽度
         */
        private int space;


        public RecycleGridDivider(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            GridLayoutManager manager = (GridLayoutManager) parent.getLayoutManager();
            int span = manager.getSpanCount();
            //为了Item大小均匀，将设定分割线平均分给左右两边Item各一半
            int offset = space / 2;
            //得到View的位置
            int childPosition = parent.getChildAdapterPosition(view);
            //第一排，顶部不画
            if (childPosition < span) {
                //最左边的，左边不画
                if (childPosition % span == 0) {
                    outRect.set(0, 0, offset, 0);
                    //最右边，右边不画
                } else if (childPosition % span == span - 1) {
                    outRect.set(offset, 0, 0, 0);
                } else {
                    outRect.set(offset, 0, offset, 0);
                }
            } else {
                //上下的分割线，就从第二排开始，每个区域的顶部直接添加设定大小，不用再均分了
                if (childPosition % span == 0) {
                    outRect.set(0, space, offset, 0);
                } else if (childPosition % span == span - 1) {
                    outRect.set(offset, space, 0, 0);
                } else {
                    outRect.set(offset, space, offset, 0);
                }
            }
        }

    }

    /**
     * 设置按键点击事件
     */
    public void setOnKeyClickListener(OnKeyClickListener listener) {
        this.onKeyClickListener = listener;
    }

    public interface OnKeyClickListener {

        void onKeyClick(String key);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
